package com.rlg.dao.Impl;

import com.rlg.dao.EbookDao;
import com.rlg.pojo.EbookEntry;
import com.rlg.util.Pager;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository(value = "ebookDao")
public class EbookDaoImpl extends HibernateDaoSupport implements EbookDao {

    @Autowired
    public SessionFactory sessionFactory;

    private Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    @Override
    public List<EbookEntry> findEbook() {
        return this.getHibernateTemplate().find("from EbookEntry ");
    }

    @Override
    public int delete(Integer id) {
        return getSession().createSQLQuery("delete from ebook_entry where id = ?").setParameter(0,id).executeUpdate();
    }

    @Override
    public int insert(EbookEntry ebook_entry) {
        return getSession().createSQLQuery("insert into ebook_entry values(E_ID.NEXTVAL,:categoryId,:title,:summary,:uploaduser,:createdate)").setProperties(ebook_entry).executeUpdate();
    }

    @Override
    public int update(EbookEntry ebook_entry) {
        return getSession().createSQLQuery("update ebook_entry set categoryId = :categoryId,title = :title,summary = :summary,uploaduser = :uploaduser,createdate = :createdate where id = :id").setProperties(ebook_entry).executeUpdate();
    }

    @Override
    public Pager pager(Pager pager, Integer categoryId) {
        try {
            pager.setHql("from Ebook_entry");
            Query query=getQuery(pager,categoryId);
            int count = query.list().size();
            //总行数获取
            pager.setRowsTotal(count);
            //防止查询越界
            int nowPage = 1;
            if(pager.getPage()<=0){
                pager.setPage(nowPage);
            }
            //指定从那个对象开始查询，参数的索引位置是从0开始的，
            query.setFirstResult((pager.getPage()-1)*pager.getRows());
            //分页时，一次最多查询的行数
            query.setMaxResults(pager.getRows());
            System.out.println("2.当前页action==================="+ pager.getPage());
            List<EbookEntry> list = query.list();
            pager.setList(list);
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return pager;
    }

    public Query getQuery(Pager pager,Integer categoryId){
        String hql = pager.getHql();
        Query query = null;
        if(categoryId!=null&&categoryId!=0){
            hql+=" where categoryId = ?";
            query = getSession().createQuery(hql).setParameter(0,categoryId);
        }else{
            query = getSession().createQuery(hql);
        }
        pager.setHql(hql);
        return query;
    }
}
